<?php

namespace app\api\Service;

use fast\Http;
use fast\Random;
use fast\Hashids;
use think\Config;
use think\Db;
use think\Validate;
use app\common\library\Auth;
use app\common\library\Sms;

class MasterthirdService
{

    public static function getOpenids($data)
    {
        $auth = Auth::instance();
        $code = $data['code'];
        if(!$code) return ['code'=>0,'msg'=>'无效的请求!','data'=>''];
        // return ['code'=>0,'msg'=>$code];
        // 获取openid和access_token
        $app_id = Config::get('site.miniappid');
        $app_secret = Config::get('site.minisecret');
        // 发送请求，获取用户openid和access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$app_id}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code";//mini
        $openidrow = json_decode(Http::get($url),true);
        
        if (empty($openidrow)) {
            return ['code' => 0, 'msg' => '获取sessin_key及openID时异常','data'=>''];
        }
        if (isset($openidrow['errcode']) && $openidrow['errcode'] != 0) {
            return ['code' => 0, 'msg' => $openidrow['errmsg'],'data'=>''];
        }
//        $res['openid'] = $openidrow['openid'];
//        $res['session_key'] = $openidrow['session_key'];

        // 获取手机号
        $res = self::getPhone(['iv'=>$data['iv'],'encryptedData'=>$data['encryptedData'],'sessionKey'=>$openidrow['session_key']]);
        if($res['code'] == 0) return ['code' => 0, 'msg' => $res['msg'],'data'=>''];

        // 授权登录
        if(isset($data['invite']) && $data['invite']) {
            $invite = $data['invite'];
        }else{
            $invite = '';
        }

        $ret = self::wechatLogin(['openid'=>$openidrow['openid'],'mobile'=>$res['data']['phoneNumber'], 'invite'=>$invite]);
        return ['code' => $ret['code'], 'msg' => $ret['msg'],'data'=>$ret['data']];
    }
    
    
    public static function getOpenid($data)
    {
        $auth = Auth::instance();
        $code = $data['code'];
        if(!$code) return ['code'=>0,'msg'=>'无效的请求!','data'=>''];
        // return ['code'=>0,'msg'=>$code];
        // 获取openid和access_token
        $app_id = Config::get('site.miniappid');
        $app_secret = Config::get('site.minisecret');
        // 发送请求，获取用户openid和access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$app_id}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code";//mini
        $openidrow = json_decode(Http::get($url),true);
        // return $openidrow;
        
        // $openidrow = json_decode('{"session_key":"CzcKZTatpqdwWksGn872gA==","openid":"ocBCh7ZIYloCBI49VJDNi6H49bec","unionid":"oHAbQ620ydYWyTeDBJc9quP70S54"}',true);
        
        if (empty($openidrow)) {
            return ['code' => 0, 'msg' => '获取sessin_key及openID时异常','data'=>''];
        }
        if (isset($openidrow['errcode']) && $openidrow['errcode'] != 0) {
            return ['code' => 0, 'msg' => $openidrow['errmsg'],'data'=>''];
        }
//        $res['openid'] = $openidrow['openid'];
//        $res['session_key'] = $openidrow['session_key'];

        // 获取手机号
        $res = self::getPhone(['iv'=>$data['iv'],'encryptedData'=>$data['encryptedData'],'sessionKey'=>$openidrow['session_key']]);
        // return $res;
        
        
        if($res['code'] == 0) return ['code' => 0, 'msg' => $res['msg'],'data'=>''];

        // 授权登录
        if(isset($data['invite']) && $data['invite']) {
            $invite = $data['invite'];
        }else{
            $invite = '';
        }

        $ret = self::wechatLogin(['openid'=>$openidrow['openid'],'unionid'=>$openidrow['unionid'],'mobile'=>$res['data']['phoneNumber'], 'invite'=>$invite]);
        return ['code' => $ret['code'], 'msg' => $ret['msg'],'data'=>$ret['data']];
    }


    // 第三方授权登录
    public static function wechatLogin($data)
    {
        $auth = Auth::instance();
        $openid = $data['openid'];
        $unionid = $data['unionid'];
        $nickname = '';
        $mobile = $data['mobile'];
        $avatar = '';

        if( isset($data['invite']) && $data['invite']){
            //解密
            $pid = \app\admin\model\User::where(['invite'=>$data['invite']])->value('id');
        }else{
            $pid = 0;
        }
        // return $this->error('测试', ['pid'=>$pid], 400);
        if (empty($openid)) {
            return ['code'=>0,'msg'=>'微信授权失败!','data'=>''];
        }

        $userinfo = \app\admin\model\User::where(['mobile' => $mobile,'group_id'=>2])->find();
        if($userinfo) {
            \app\admin\model\User::where(['mobile' => $mobile,'group_id'=>2])->update(['openid'=>$openid,'unionid'=>$unionid]);
            $auth->direct($userinfo['id']);
            $userinfo = $auth->getUserinfo();
            return ['code'=>1,'msg'=>'登录成功!','data'=>$userinfo];
        }else{
            if (empty($nickname)) $nickname = '电工' . Random::numeric(6);
            if (empty($mobile)) return ['code'=>0,'msg'=>'手机号错误','data'=>''];
//            if (empty($nickname)) $nickname = substr_replace($mobile, '****', 3, 4);
            if (empty($avatar)) $avatar = request()->domain().'/assets/img/avatar.png';

            $user = new \app\admin\model\User();
            $salt = Random::alnum();
            $password = '123456';
            $user->data([
                'group_id'      => 2,
                'nickname'      => $nickname,
                'avatar'        => $avatar,
                'mobile'        => $mobile,
                'password'      => $auth->getEncryptPassword($password,$salt),
                'salt'          => $salt,
                'status'        => 'normal',
                'openid'        => $openid,
                'unionid'       => $unionid,
                'pid'           => $pid,
                'invite'        => generateUniqueNumber()
            ]);
            $user->save();
            $result = $auth->direct($user->id);
            if ($result) {
                // 上级奖励积分
                if($pid) {
                    $invite_reward = Config::get('site.invite_reward');
                    \app\common\model\User::score($invite_reward, $pid, '邀请注册奖励');
                }
                $userinfo = $auth->getUserinfo();
                return ['code'=>1,'msg'=>'登录成功!','data'=>$userinfo];
            } else {
                return ['code'=>0,'msg'=>'登录失败','data'=>''];
            }
        }
    }

    /**
     * 获取手机号
     */
    public static function getPhone($data)
    {
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];
        $sessionKey = $data['sessionKey'];
        $appid = Config::get('site.miniappid');
//        $datainfo = $this->auth->getUserinfo();
        if (!$iv || !$encryptedData) {
            return ['code'=>0,'msg'=>'无效的参数','data'=>''];
        }
        $errCode = self::decryptData($encryptedData, $iv, $data, $sessionKey, $appid);
        
        
        
        if ($errCode == 0) {
            $result = json_decode($data, true);

            if (isset($result['phoneNumber'])) {
//                $user = \app\admin\model\User::get($datainfo['user_id']);
//                $user->mobile = $result['phoneNumber'];
//                $user->save();
                return ['code'=>1,'msg'=>'获取成功','data'=>$result];
            } else {
                return ['code'=>0,'msg'=>'获取失败','data'=>''];
            }
        } else {
            return ['code'=>0,'msg'=>'获取用户信息失败','data'=>''];
        }
    }

    // 绑定微信
    public static function bindWechat($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $code = $data['code'];
        if(!$code) return ['code'=>0,'msg'=>'无效的请求!','data'=>''];
        // return ['code'=>0,'msg'=>$code];
        // 获取openid和access_token
        $app_id = Config::get('site.miniappid');
        $app_secret = Config::get('site.minisecret');
        // 发送请求，获取用户openid和access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$app_id}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code";//mini
        $openidrow = json_decode(Http::get($url),true);
        if (empty($openidrow)) {
            return ['code' => 0, 'msg' => '获取sessin_key及openID时异常','data'=>''];
        }
        if (isset($openidrow['errcode']) && $openidrow['errcode'] != 0) {
            return ['code' => 0, 'msg' => $openidrow['errmsg'],'data'=>''];
        }

        if(!$user_id)  return ['code'=>0,'msg'=>'请先登录','data'=>''];
        $user = \app\admin\model\User::where(['id' => $user_id])->find();
        $user->openid = $openidrow['openid'];
        $result = $user->save();
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>['openid'=>$openidrow['openid']]];
        } else {
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    public static function saveOpenid($data)
    {
        $auth = Auth::instance();
        $code = $data['code'];
        if(!$code) return ['code'=>0,'msg'=>'无效的请求!','data'=>''];
        // return ['code'=>0,'msg'=>$code];
        // 获取openid和access_token
        $app_id = Config::get('site.miniappid');
        $app_secret = Config::get('site.minisecret');
        // 发送请求，获取用户openid和access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$app_id}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code";//mini
        $openidrow = json_decode(Http::get($url),true);
        if (empty($openidrow)) {
            return ['code' => 0, 'msg' => '获取sessin_key及openID时异常','data'=>''];
        }
        if (isset($openidrow['errcode']) && $openidrow['errcode'] != 0) {
            return ['code' => 0, 'msg' => $openidrow['errmsg'],'data'=>''];
        }
        $res['openid'] = $openidrow['openid'];
        $user = new \app\admin\model\User;
        $result = $user->save(['openid'=>$res['openid']],['id'=>$auth->id]);

        return ['code' => 1, 'msg' => '操作成功','data'=>['openid'=>$res['openid']]];
    }


    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public static function decryptData($encryptedData, $iv, &$data, $sessionKey, $appid)
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return -41003;
        }
        if ($dataObj->watermark->appid != $appid) {
            return -41003;
        }
        $data = $result;
        return 0;
    }

}
